﻿using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Akso.Authorization;
using Akso.Entities;
using Akso.Schools.Dto;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Akso.Schools
{
    public class SchoolAppService: AbpZeroTemplateAppServiceBase, ISchoolAppService
    {
        private readonly IRepository<School, Guid> _schoolsRepository;

        public SchoolAppService(IRepository<School, Guid> schoolsRepository)
        {
            _schoolsRepository = schoolsRepository;

        }

        public async Task<ListResultDto<SchoolListDto>> GetSchools()
        {
            //var query =
            //    from ou in _schoolsRepository.GetAll()
            //    join uou in _userOrganizationUnitRepository.GetAll() on ou.Id equals uou.OrganizationUnitId into g
            //    select new { ou, memberCount = g.Count() };
            var query = _schoolsRepository.GetAll();
            var items = await query.ToListAsync();

            return new ListResultDto<SchoolListDto>(
                items.Select(item =>
                {
                    var dto = item.MapTo<SchoolListDto>();
                    //dto.MemberCount = item.memberCount;
                    return dto;
                }).ToList());
        }

        #region 新增、编辑对象，带权限检查
        /// <summary>
        /// 新增、编辑对象，带权限检查。
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(AppPermissions.Pages_BasicDataModule_Classrooms_Create, AppPermissions.Pages_BasicDataModule_Classrooms_Edit)]
        public async Task<School> CreateOrUpdateObject(CreateOrUpdateSchoolInput input)
        {
            if (input.School.Id.HasValue)
            {
                return await UpdateObject(input);
            }
            else
            {
                return await CreateObject(input);
            }
        }

        /// <summary>
        /// 新增对象，带权限检查。
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(AppPermissions.Pages_BasicDataModule_Schools_AddRoot)]
        protected virtual async Task<School> CreateObject(CreateOrUpdateSchoolInput input)
        {
            var o = input.School.MapTo<School>();
            if (AbpSession.TenantId != null)
                o.TenantId = (int)AbpSession.TenantId;
            else
                o.TenantId = 1; //不能赋值0，估计框架有要求
            //检查名称是否存在
            int i = await _schoolsRepository.CountAsync(x => x.SchoolName == o.SchoolName);
            if (i > 0)
            {

                Debug.Fail(L("YouCanNotDeleteOwnAccount"));
            }
            return await _schoolsRepository.InsertAsync(o);
        }
        /// <summary>
        /// 编辑对象，带权限检查。
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(AppPermissions.Pages_BasicDataModule_Schools_Edit)]
        protected virtual async Task<School> UpdateObject(CreateOrUpdateSchoolInput input)
        {
            Debug.Assert(input.School.Id != null, "input.Classroom.Id should be set.");

            var o = await _schoolsRepository.GetAsync(input.School.Id.Value);
            //Update classroom properties
            input.School.MapTo(o);
            return await _schoolsRepository.UpdateAsync(o);
        }
        #endregion

        #region 根据Guid获取数据对象
        /// <summary>
        /// 新增、编辑页面中获取对象，带权限检查。
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(AppPermissions.Pages_BasicDataModule_Schools_AddRoot, AppPermissions.Pages_BasicDataModule_Schools_Edit)]
        public async Task<GetSchoolForEditOutput> GetObjectForEdit(NullableIdDto<Guid> input)
        {
            var output = new GetSchoolForEditOutput
            {

            };

            if (!input.Id.HasValue)
            {
                //Creating a new object
                output.School = new SchoolEditDto();
            }
            else
            {
                //Editing an existing object
                var existingObject = await _schoolsRepository.GetAsync(input.Id.Value);

                output.School = existingObject.MapTo<SchoolEditDto>();
            }

            return output;
        }
        #endregion

        #region 删除数据，带权限检查
        /// <summary>
        /// 删除对象，带权限检查。
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(AppPermissions.Pages_BasicDataModule_Schools_Delete)]
        public async Task DeleteSchool(EntityDto<Guid> input)
        {
            var o = await _schoolsRepository.GetAsync(input.Id);
            await _schoolsRepository.DeleteAsync(o);
        }
        #endregion

        #region 抓取所有学校
        /// <summary>
        /// 抓取所有学校
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ListResultDto<SchoolListDto> GetAllSchools()
        {
           
            var schoolList = _schoolsRepository.GetAll().Where(x => x.OrgType == 1).ToList();
            return new ListResultDto<SchoolListDto>(schoolList.MapTo<List<SchoolListDto>>());
        }
        #endregion
    }
}
